<?php

declare(strict_types=1);

namespace app\api\controller\v1;

use app\api\BaseApiController;
use think\facade\Request;
use think\facade\Filesystem;
use think\facade\Config;
use app\system\model\LogOperate as Log;
use think\Image;

class Upload extends BaseApiController
{
    /**
     * 头像上传
     * url: http://域名/api/v1/upload
     * doc: http://lutui.net/doc/app/profile-avatar.html
     */
    public function index()
    {
        $file = Request::file('file');
        $pre = Config::get('filesystem.disks.public.url');
        $filename = Filesystem::putFile('image', $file);
        $path = Config::get('filesystem.disks.public.root') . '/';
        $image = $path . $filename;
        $info = getimagesize($image);
        // 判断上传的文件是否为图片
        if (!in_array($info[2], [2, 3])) {
            return json(['error' => '请选择图片上传', 'url' => '']);
        }
        // 生成缩略图
        $im = Image::open($image);
        $im->thumb(200, 200)->save($image);
        $url = $pre . '/' . $filename;
        $this->user->avatar = $url;
        $this->user->save();
        Log::add('更新头像', [
            'ID' => UID,
            '昵称' => USERNAME,
            '头像' => $url,
        ]);
        return json(['error' => '', 'url' => DOMAIN . $url]);
    }
}
